import { getToken } from '~/utils/auth';
import { isTokenExpiredError, handleTokenExpiredError, checkAndHandleAuthError } from '~/utils/auth-error-handler';

Page({
  data: {
    points: 0,
    history: [],
    loading: false,
    page: 1,
    hasMore: true
  },

    // 处理充值按钮点击
  // 点击事件
  handleRecharge() {
    console.log("点击")
    wx.showModal({
      title: '充值提示',
      content: '充值请联系管理员',
      showCancel: false,
    });
  },

  async onLoad() {
    await this.loadPointsInfo();
    await this.loadPointsHistory();
  },

  async loadPointsInfo() {
    try {
      const token = getToken();
      if (!token) {
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        });
        return;
      }

      const result = await wx.cloud.callFunction({
        name: 'points-management',
        data: {
          action: 'getPoints',
          token: token,
          data: {}
        }
      });

      // 检查是否为token过期错误
      if (checkAndHandleAuthError(result, {
        customMessage: '积分信息已过期，请重新登录'
      })) {
        return;
      }

      if (result.result.success) {
        this.setData({
          points: result.result.data.points
        });
      }
    } catch (error) {
      console.error('获取积分信息失败:', error);
    }
  },

  async loadPointsHistory() {
    if (this.data.loading || !this.data.hasMore) return;

    this.setData({ loading: true });

    try {
      const token = getToken();
      if (!token) return;

      const result = await wx.cloud.callFunction({
        name: 'points-management',
        data: {
          action: 'getPointsHistory',
          token: token,
          data: {
            page: this.data.page,
            limit: 20
          }
        }
      });

      // 检查是否为token过期错误
      if (checkAndHandleAuthError(result, {
        customMessage: '积分信息已过期，请重新登录'
      })) {
        this.setData({ loading: false });
        return;
      }

      if (result.result.success) {
        const newHistory = result.result.data.list;
        this.setData({
          history: this.data.page === 1 ? newHistory : [...this.data.history, ...newHistory],
          hasMore: newHistory.length === 20,
          page: this.data.page + 1
        });
      }
    } catch (error) {
      console.error('获取积分历史失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  onReachBottom() {
    this.loadPointsHistory();
  },

  onPullDownRefresh() {
    this.setData({
      page: 1,
      hasMore: true,
      history: []
    });
    Promise.all([
      this.loadPointsInfo(),
      this.loadPointsHistory()
    ]).finally(() => {
      wx.stopPullDownRefresh();
    });
  },

  formatTime(time) {
    const date = new Date(time);
    return `${date.getMonth() + 1}-${date.getDate()} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  },

  getTypeText(type) {
    const typeMap = {
      'consume': '消费',
      'recharge': '充值',
      'reward': '奖励'
    };
    return typeMap[type] || type;
  },

  getTypeColor(type) {
    const colorMap = {
      'consume': '#e34d59',
      'recharge': '#00a870',
      'reward': '#0052d9'
    };
    return colorMap[type] || '#666';
  },

  // 查看历史记录
  handleViewHistory() {
    // 刷新历史记录
    this.setData({
      page: 1,
      hasMore: true,
      history: []
    });
    this.loadPointsHistory();
  },

  // 查看全部历史记录
  handleViewAllHistory() {
    wx.showToast({
      title: '下拉刷新查看更多记录',
      icon: 'none',
      duration: 2000
    });
  },

  // 联系客服
  handleContact() {
    wx.showModal({
      title: '联系管理员',
      content: '请添加管理员微信或联系客服进行积分充值等相关事宜。',
      showCancel: true,
      cancelText: '取消',
      confirmText: '复制微信号',
      success: (res) => {
        if (res.confirm) {
          // 这里可以复制管理员微信号到剪贴板
          wx.setClipboardData({
            data: 'admin_wechat_id', // 替换为实际的管理员微信号
            success: () => {
              wx.showToast({
                title: '微信号已复制',
                icon: 'success'
              });
            }
          });
        }
      }
    });
  }
}); 